<template>
  <div class="login">
    <!-- <h2 class="login-logo"> -->
    <!-- <img src="../assets/images/tilogo.png" alt="" /> -->
    <!-- </h2> -->
    <h2 class="login-title">石洞口煤气制气安全管理信息化平台</h2>
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
        >
          <template #prefix
            ><svg-icon icon-class="user" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon icon-class="password" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon icon-class="validCode" class="el-input__icon input-icon"
          /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 0px"
        >记住密码</el-checkbox
      >
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'"
            >立即注册</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <div class="el-login-footer">
      <img :src="appCodeUrl" @error="onCodeError" alt="" />
    </div>
    <!-- 加备案号 -->
    <p class="footer-p">沪ICP备2024055866号</p>
    <el-dialog
      append-to-body
      v-model="qyDialog"
      width="30%"
      title="第一次登录需要重新设置密码"
    >
      <template #default>
        <el-form label-width="100px" label-position="left" ref="refQyForm">
          <el-form-item label="新密码">
            <el-input type="password" v-model="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input type="password" v-model="password2"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="close">取 消</el-button> -->
          <el-button type="primary" @click="onSubmit()"> 确 认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getCodeImg,
  getAppImage,
  checkFirstLogin,
  resetPsd,
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import { getUserProfile } from "@/api/system/user";
import CryptoJS from "crypto-js/crypto-js";

const route = useRoute();

const appCodeUrl = ref(false);
getAppImage().then((res) => {
  appCodeUrl.value = res.msg;
});
const userStore = useUserStore();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
// 注册开关
const register = ref(false);
const redirect = ref(route.query.redirect);

const userInfo = ref({});
// 加密 这里使用的是CBC模式 必须要设置偏移量
function encryptData(encryptData) {
  const data = CryptoJS.enc.Utf8.parse(JSON.stringify(encryptData)); // 转义一下数据
  const key = CryptoJS.enc.Utf8.parse("digital20230221o"); // 秘钥 需要设置16位
  const iv = CryptoJS.enc.Utf8.parse("digital20230221o"); // 偏移量
  const encrypted = CryptoJS.AES.encrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore
        .login({
          ...loginForm.value,
          // password: encryptData(loginForm.value.password),
        })
        .then(() => {
          loading.value = false;
          getUserProfile().then((res) => {
            userInfo.value = res.data;
            localStorage.setItem("USER_INFO", JSON.stringify(res.data));
            checkFirstLogin().then((res) => {
              if (res.data.firstLogin == 0) {
                qyDialog.value = true;
              } else {
                router.push({ path: redirect.value || "/" });
              }
            });
          });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

function getCode() {
  getCodeImg().then((res) => {
    // return
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}
// 修改密码逻辑
const password = ref("");
const password2 = ref("");
const qyDialog = ref(false);
const checkPassword = () => {
  let regex = /(?=.*[0-9])(?=.*[a-zA-Z]).{8,16}/;
  if (!regex.test(password.value)) {
    proxy.$modal.msgError("密码复杂度太低，需包含数字和字母且长度8到16位");
    return false;
  } else if (password.value != password2.value) {
    proxy.$modal.msgError("两次输入密码不一致");

    return false;
  }
  return true;
};

const onSubmit = () => {
  const res = checkPassword();
  if (res) {
    resetPsd({
      userId: userInfo.value.userId,
      password: password.value,
    }).then((res) => {
      proxy.$modal.msgSuccess("修改成功，请重新登录");
      loading.value = false;

      qyDialog.value = false;
      userStore.logOut();
    });
  }
};
getCode();
getCookie();
const onCodeError = (e) => {
  if (appCodeUrl.value === false) {
    return;
  }
  e.target.style.display = "none";
};
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  flex-direction: column;
  // justify-content: center;
  padding-top: 180px;
  align-items: center;
  height: 100%;
  background-color: #707070;
  background-image: url("../assets/images/loginbg.jpg");
  background-size: cover;
  &-logo {
    width: 120px;
    img {
      width: 100%;
    }
  }

  &-title {
    color: #fff;
    font-weight: 700;
    font-size: 40px;
  }
}
.title {
  margin: 0px auto 60px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #359bc3;
  width: 400px;
  margin-top: 50px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    background: #359bc3;

    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 240px;
  width: 240px;
  // line-height: 40px;
  position: fixed;
  bottom: 10px;
  right: 10px;
  // text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  img {
    width: 240px;
    height: 240px;
  }
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
.footer-p{
  width: 100%;
  color: #fff;
  text-align: center;
  position: absolute;
  bottom: 20px;
}
</style>
